package com.xiaohui.controller;


import com.xiaohui.utils.MinioUtils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.*;
@Component
public class ReadTest {


    @Autowired
    private MinioUtils minioUtils;



    private static ReadTest ReadTest;

    @PostConstruct
    public void init(){
        ReadTest = this;
        ReadTest.minioUtils = this.minioUtils;
    }



    public void readAW(String path) throws IOException {

        System.out.println("新建11111：" + path);


        File file = new File(path);

        FileItem fileItem = createFileItem(file, file.getName());

        MultipartFile mfile = new CommonsMultipartFile(fileItem);



        ReadTest.minioUtils.upload(mfile, mfile.getName());


    }

    /*
        创建FileItem
         */
    private FileItem createFileItem(File file, String fieldName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }



}
